import React, {PureComponent} from "react";
import {connect} from "react-redux";
import {Form} from "antd";
import {query, saveFilter} from "./actions";
import FilterForm from "../../components/FilterForm";
import {formatDate, formatStrToDate} from "../../lib/func";
import {getPrincipal, saveLastFilter} from "../../lib/identity";
const LAST_FILTER = "orderProfit";

class Filter extends PureComponent {
    handleSearch = (values) => {
        const {dispatch} = this.props;
        let fields = values;
        this.setState({...values});
        if (fields.createTimeRange && fields.createTimeRange.length > 1) {
            fields.createTimeStart = formatDate(fields.createTimeRange[0]);
            fields.createTimeEnd = formatDate(fields.createTimeRange[1]);
        }
        dispatch(saveFilter({...values}));
        saveLastFilter(LAST_FILTER, {...values});
        dispatch(query({...values, "userId": getPrincipal().id}));
    };

    render() {
        const {loading, filter, organizations} = this.props;
        filter.createTimeRange = [formatStrToDate(filter.createTimeStart), formatStrToDate(filter.createTimeEnd)];
        const filterSchema = [
            {
                key: 'orgIdList',
                field: 'orgIdList',
                type: 'treeSelector',
                expandable: true,
                width: 200,
                title: '财务归属',
                controlProps: {
                    treeData: organizations,
                    labelField: "name",
                    valueField: "id",
                    treeCheckable: true
                },
                fieldOptions: {
                    initialValue: filter.orgIdList
                }
            }, {
                key: 'createTimeRange',
                field: 'createTimeRange',
                type: 'dateRangePicker',
                expandable: true,
                title: '班列/提货日期',
                fieldOptions: {
                    initialValue: filter.createTimeRange
                }
            }
        ];

        return (
            <FilterForm schema={filterSchema} callback={this.handleSearch} loading={loading}/>
        );
    }
}

const mapStateToProps = state => {
    return {
        ...state.orderProfit.list,
        clientList: state.home.clients,
        carrierList: state.home.carriers,
        organizations: state.organization.list.dataSource
    };
};

export default connect(mapStateToProps)(Form.create()(Filter));
